# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# A bunch of packages run `python_set_active_version 2` in their pkg_setup
# in order to set the system python interp to version 2.x.  The problem is
# that it ends up encoding the active python ABI in the binpkg's env.  So
# when you try to emerge it later, it requires the exact same python ver
# to be available (e.g. 2.6).  Ignoring the stupidness of this for binpkgs
# (as there's an open Gentoo bug on the topic), let's force the binpkgs to
# be rebuilt.

set -e

OLD_PY_VER="2.6"

export CLEAN_DELAY=0

find_pkgs() {
  find "${root}"/var/db/pkg/ -name environment.bz2 \
    -exec bzgrep "PYTHON_ABI=\"${OLD_PY_VER}\"" {} + | \
    sed -r 's:.*/var/db/pkg/(.*)/environment.bz2.*:\1:'
}

update_pkgs() {
  # Try and update/rebuild any packages.
  info "${board}: searching for packages using python-${OLD_PY_VER}"
  local pkgs=( $(find_pkgs) )
  if [[ ${#pkgs[*]} -gt 0 ]]; then
    # Note: we allow this stage to fail because the binpkgs might be old
    # and relying on python-2.6.  Since we nuked that version though, most
    # will fail to even emerge.
    info "${board}: trying to update via binpkgs"
    sudo ${emerge} -q1g "${pkgs[@]/#/>=}" || :

    pkgs=( $(find_pkgs) )
    if [[ ${#pkgs[*]} -gt 0 ]]; then
      info "${board}: forcing rebuild from source"
      sudo ${emerge} -q1 "${pkgs[@]/#/>=}"
    fi
  fi
}

b() {
  local cmd=$1 root=$2 board=$3
  local emerge="/mnt/host/source/chromite/bin/parallel_emerge"
  local qfile="qfile"
  if [[ ${root} != "/" ]]; then
    emerge+=" --board=${board}"
    qfile+="-${board}"
  fi
  "$@"
}

# Update host sdk first before we update the boards.  We have to
# do this specially since the package manager is based on python.
b update_pkgs / host_sdk

# Update board packages in serial (might build from source).
for board_root in /build/*; do
  board=${board_root##*/}
  b update_pkgs ${board_root} ${board}
done

wait
